package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.CheckItemDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author hql
 * @date 2019-12-01 12:57
 */
@Service(interfaceClass = CheckItemService.class)
@Transactional
public class CheckItemServiceImpl implements CheckItemService {

    @Autowired
    private CheckItemDao checkItemDao;
    @Override
    public void add(CheckItem checkItem) {
        checkItemDao.add(checkItem);
    }

    @Override
    public PageResult find(QueryPageBean queryPageBean) {

        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());

        String queryString = queryPageBean.getQueryString();
        if (queryString!=null){
            StringBuilder sb = new StringBuilder();
            sb.append("%").append(queryString).append("%");
            queryString=sb.toString();
          //  queryPageBean.setCurrentPage(1);
            queryPageBean.setQueryString(queryString);
        }
        List<CheckItem> checkItems = checkItemDao.find(queryPageBean);
        PageInfo<CheckItem> pageInfo=new PageInfo<CheckItem>(checkItems);

        if (queryPageBean.getCurrentPage()>pageInfo.getLastPage()){
            PageHelper.startPage(pageInfo.getLastPage(),queryPageBean.getPageSize());
            List<CheckItem>  checkItems2 = checkItemDao.find(queryPageBean);
            PageInfo<CheckItem> pageInfo2=new PageInfo<CheckItem>(checkItems2);
            long total = pageInfo2.getTotal();
            return new PageResult(total,checkItems2);
        }else {
            long total = pageInfo.getTotal();
            return new PageResult(total, checkItems);
        }
    }

    @Override
    public CheckItem findById(String code) {
        CheckItem checkItem=  checkItemDao.findById(code);
        return checkItem;
    }

    @Override
    public void updateCheckItem(CheckItem checkItem) {
        checkItemDao.updateCheckItem(checkItem);
    }

    /**
     * 删除检查项
     * @param id
     */
    @Override
    public void delById(Integer id) {
       Integer count = checkItemDao.findBy(id);
       if (count==0){
           checkItemDao.delById(id);
       }else {
          throw new RuntimeException("有从表");
       }
    }
}
